const mongoose = require('mongoose');

const News = mongoose.model('News');
module.exports = {
  create: (req, res, next) => {
    const news = new News(req.body);
    news.save((err) => {
      if (err) {
        return next(err);
      }
      return res.json(news);
    });
  },
  list: (req, res, next) => {
    const pageSize = parseInt(req.query.pageSize, 10) || 10;

    const pageStart = parseInt(req.query.pageStart, 10) || 1;

    News.find().skip(pageSize * (pageStart - 1)).limit(pageSize).exec((err, data) => {
      if (err) {
        return next(err);
      }
      return res.json(data);
    })
  },
  getNewsId: (req, res, next, id) => {
    if (!id) {
      return next(new Error('id not exist'));
    }
    News.findOne({_id: id}).exec((err, data) => {
      if (err) {
        return next(err);
      }
      if (!data) {
        return next(new Error('对应的news详情不存在'));
      }
      // 这里是为了在下面进行使用
      req.news = data;
      return next();
    })
  },
  get: (req, res, next) => {
    return res.json(req.news);
  }
}